package com.alterzhang.userservice.proxy.zshproxy;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * 代码的生成  编译从新加载到jvm中
 */
public class zshClassLoader extends ClassLoader {

    private File baseDir;

    public zshClassLoader() {
        String path = zshClassLoader.class.getResource("").getPath();
        this.baseDir = new File(path);
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        String className = zshClassLoader.class.getPackage().getName() + "." + name;

        if (null != baseDir) {
            File classFile = new File(baseDir, name.replace("\\.", "/") + ".class");
            if (classFile.exists()) {
                FileInputStream fileInputStream = null;
                ByteArrayOutputStream baos = null;
                try {
                    fileInputStream = new FileInputStream(classFile);
                    //读到内存中以后清楚
                    classFile.delete();
                    baos = new ByteArrayOutputStream();
                    byte[] b = new byte[1024];
                    int len;
                    while ((len = fileInputStream.read(b)) != -1) {
                        baos.write(b, 0, len);

                    }
                    return defineClass(className, baos.toByteArray(), 0, baos.size());
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    try {
                        if (fileInputStream != null) {
                            fileInputStream.close();
                        }
                        if (null != baos) {
                            baos.close();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

        return null;
    }
}
